package org.chench.extra;

import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

/**
 * @author chench9@lenovo.com
 * @desc org.chench.extra.HelloWorldServer
 * @date 3/20/19 11:01 AM
 */
public class HelloWorldServer {
    public static void main(String[] args) {
        try {
            startServerByJeromq();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 使用ZeroMQ的纯Java实现版本jeromq
    private static void startServerByJeromq() throws InterruptedException {
        try(ZContext context = new ZContext()){
            // 创建被动接收请求的Socket
            ZMQ.Socket socket = context.createSocket(SocketType.REP);
            socket.bind("tcp://*:5555");
            System.out.println("Start server on 5555 ...");
            while(!Thread.currentThread().isInterrupted()) {
                byte[] bytes = socket.recv(0);
                String req = new String(bytes, ZMQ.CHARSET);
                System.out.println("Received: [" + req + "]");
                String resp = "Hello, " + req;
                socket.send(resp.getBytes(ZMQ.CHARSET), 0);
                Thread.sleep(1000);
            }
        }
    }

    // 用过jzmq使用libzmq
    private static void startServerByJzmq() throws InterruptedException {
        try(ZContext context = new ZContext()){
            // 创建被动接收请求的Socket
            ZMQ.Socket socket = context.createSocket(ZMQ.REP);
            socket.bind("tcp://*:5555");
            System.out.println("Start server on 5555 ...");
            while(!Thread.currentThread().isInterrupted()) {
                byte[] bytes = socket.recv(0);
                String req = new String(bytes);
                System.out.println("Received: [" + req + "]");
                String resp = "Hello, " + req;
                socket.send(resp.getBytes(), 0);
                Thread.sleep(1000);
            }
        }
    }
}
